import bfconsole from '../utils/bf-console'
import bfstore from './bf-store'

export default {
    // 添加组织节点
    setOrgNodeTooltip(org) {
        return org.fullName;
    },
    setOrgNodeTitle(org, showTag = true) {
        let title = "";
        // icon
        title += `<img src="${org.fileContent}" class='org-icon'>`;
        // name
        title += `<span class="bftree_org_name">${org.shortName}</span>`;
        // 设备在线数量和总数标签tag
        if (showTag && org.totalCount > 0) {
            title += `<span class="device_count_tag">
                    <span class="device_online">${org.onlineCount}</span>/<span 
                    class="device_total">${org.totalCount}</span>
                </span>`;
        }

        return title;
    },
    setTreeOrgNode(org, showTag) {
        // sortValue 为节点自定义排序值，当排序值相等时使用sortName按名称排序
        // filterValue 为节点自定义过滤值
        return {
            title: this.setOrgNodeTitle(org, showTag),
            tooltip: this.setOrgNodeTooltip(org),
            folder: true,
            expanded: true,
            key: org.rid,
            icon: false,
            selected: false,
            sortValue: org.sortValue,
            sortName: org.shortName,
            filterValue: org.shortName
        }
    },
    addTreeOrgNode(parentNode, org, showTag) {
        let child = this.setTreeOrgNode(org, showTag);
        return this.parentNodeAddChildren(parentNode, child);
    },
    // 加载组织节点
    addOrgNodeToTree(treeId, rootNode, org, showTag) {
        let $tree = $(treeId);
        // 获取父组织的树节点，如果没有则先挂载父节点，再添加己节点
        let parentNode = $tree.fancytree("getTree").getNodeByKey("" + org.parentId);
        if (!parentNode) {
            // fancytree父节点不存在，获取父组织数据
            let parentOrgData = bfstore.getters.getOrgItem(org.parentId);
            // 没有父组织数据，则用树根节点作为父节点
            if (!parentOrgData) {
                parentNode = rootNode;
            } else {
                // 得到父组织数据后，先挂载父节点
                parentNode = this.addOrgNodeToTree(treeId, rootNode, parentOrgData, showTag);
            }
        }

        // 最后挂载己节点
        return this.addTreeOrgNode(parentNode, org, showTag);
    },
    // 遍历组织数据，通过组织的rid获取父组织的树节点，将组织挂载到父节点上。
    initTreeOrgNode(treeId, showTag) {
        let $tree = $(treeId);
        let rootNode = $tree.fancytree('getRootNode');
        for (let k in bfstore.state.dbOrg.datas) {
            let org = bfstore.state.dbOrg.datas[k];
            // 如果当前组织已经挂载到fancytree上，则跳过
            let current_node = $tree.fancytree("getTree").getNodeByKey("" + org.rid);
            if (current_node) {
                continue;
            }
            this.addOrgNodeToTree(treeId, rootNode, org, showTag);
        }
    },


    // fancytree common api
    parentNodeAddChildren(parentNode, child) {
        return parentNode.addChildren(child);
    },
    addTreeNode(nodeData, type = 0) {
        bfconsole.log("addTreeNode:", nodeData);
        // 先获取fancytree中父节点，再通过父节点添加已节点
        let orgId = "" + nodeData.orgId;
        let method = "addTreeDeviceNode";
        if (type === 1) {
            orgId = "" + nodeData.parentId;
            method = "addTreeOrgNode";
        }
        let parentNode = $("#orgDevTree").fancytree("getTree").getNodeByKey(orgId);
        if (!parentNode) {
            parentNode = $("#orgDevTree").fancytree("getRootNode");
        }
        this[method] && this[method](parentNode, nodeData);
    },
    updateTreeNodeTitle(nodeData, type = 0) {
        // 通过rid获取fancytree节点，重置节点数据，再更新节点
        let key = "" + nodeData.rid;
        let node = $("#orgDevTree").fancytree("getTree").getNodeByKey(key);
        if (!node) {
            bfconsole.error("can not found tree node ", nodeData);
            return
        }

        let title = "";
        if (type === 1) {
            title = this.setOrgNodeTitle(nodeData);
            node.tooltip = this.setOrgNodeTooltip(nodeData);
        } else if (type === 2) {
            title = this.setGroupNodeTitle(nodeData);
            node.tooltip = this.setGroupNodeTooltip(nodeData);
        } else {
            title = this.setDeviceNodeTitle(nodeData);
            node.tooltip = this.setDeviceNodeTooltip(nodeData);
        }

        node.setTitle(title);
    },
    deleteTreeNode(nodeData) {
        bfconsole.log("deleteTreeNode:", nodeData);
        // 通过rid获取fancytree节点，删除节点
        let key = "" + nodeData.rid;
        let node = $("#orgDevTree").fancytree("getTree").getNodeByKey(key);
        if (!node) {
            bfconsole.error("can not found tree node ", nodeData);
            return
        }
        if (node.hasChildren()) {
            node.removeChildren();
        }
        node.remove();
    },
    changeTreeNode(newnode) {
        try {
            let key;
            if (newnode.parentId != null) {
                key = "" + newnode.parentId;
            } else {
                key = "" + newnode.orgId;
            }
            let source = $("#orgDevTree").fancytree("getTree").getNodeByKey("" + newnode.rid);
            let target = $("#orgDevTree").fancytree("getTree").getNodeByKey(key);
            source && target && source.moveTo(target, "child");
            // 节点改变上级组织后，需要重新统计所有下属设备数量
            this.reloadDeviceCount();
            // 更新目标的组织节点排序功能
            this.sortTargetChildren(target);
        } catch (err) {
            bfconsole.error("changeTreeNodeErr", err);
        }
    },
    selectAll(treeId, state) {
        let tree = $(`#${treeId}`).fancytree("getRootNode");
        if (tree) {
            tree.visit((node) => {
                node.setSelected(state);
            });
        }
    },
    expandAll(treeId, state) {
        let tree = $(`#${treeId}`).fancytree("getRootNode");
        if (tree) {
            tree.visit((node) => {
                node.setExpanded(state);
            });
        }
    },
    showAllDev(treeId) {
        let tree = $(`#${treeId}`).fancytree("getRootNode");
        if (tree) {
            tree.visit((node) => {
                if (!node.isFolder()) {
                    $(node.li).show();
                }
            });
        }
    },
    testDeviceIsOnline(key) {
        let devices = bfstore.state.dbDevice.datas;
        let dev = devices[key];
        if (!dev) {
            bfconsole.error("can not found device of key:", key);
            return false;
        }
        // 假设设备有"online"属性标志设备在线
        if (!dev["online"]) {
            return false
        }
        return true;
    },
    showOnlineDev(treeId) {
        let tree = $(`#${treeId}`).fancytree("getRootNode");
        if (tree) {
            tree.visit((node) => {
                if (!node.isFolder()) {
                    let key = node.key;
                    let state = this.testDeviceIsOnline(key);
                    if (state) {
                        $(node.li).show();
                    } else {
                        $(node.li).hide();
                    }
                }
            });
        }
    },

    // 添加设备节点
    setDeviceNodeTooltip(device) {
        return device.selfId + "/" + device.dmrId;
    },
    setDeviceNodeTitle(device) {
        let title = "";
        // icon
        title += `<i class='bf-icon gw-interphone'></i>`;
        // device name
        title += `<span class="bftree_device_name">${device.name}</span>`;
        // user name, deviceUser==0 则没有指定用户
        if (device.deviceUser !== 0) {
            let userData = bfstore.getters.getUserItem(device.deviceUser);
            if (userData) {
                title += `<span class="bftree_user_name">${userData.name}</span>`;
            }
        }

        return title;
    },
    setTreeDeviceNode(device) {
        // sortValue 为节点自定义排序值，当排序值相等时使用sortName按名称排序
        // filterValue 为节点自定义过滤值
        let username = "";
        if (device.deviceUser !== 0) {
            let userData = bfstore.getters.getUserItem(device.deviceUser);
            if (userData) {
                username += userData.name;
            }
        }
        return {
            title: this.setDeviceNodeTitle(device),
            tooltip: this.setDeviceNodeTooltip(device),
            key: device.rid,
            icon: false,
            selected: false,
            sortValue: device.sortValue,
            sortName: device.name,
            filterValue: device.name + username
        }
    },
    addTreeDeviceNode(parentNode, org) {
        let child = this.setTreeDeviceNode(org);
        return this.parentNodeAddChildren(parentNode, child);
    },

    // todo 统计组织下所有设备总数和在线总数
    initOrgHasDeviceCount() {
        for (let i in bfstore.state.dbOrg.datas) {
            let orgData = bfstore.state.dbOrg.datas[i];
            orgData.onlineCount = 0;
            orgData.ownDeviceCount = 0;
            orgData.totalCount = -1;
        }
    },
    calcOrgHasDeviceCount(device) {
        // 通过orgId获取上级组织数据
        let orgData = bfstore.getters.getOrgItem(device.orgId);
        if (!orgData) {
            return
        }
        orgData.ownDeviceCount++;
    },
    calcOrgHasDeviceTotalCount(org) {
        let sub_org = [];
        // 找到org的直属组织，push到sub_org中，以计算org下所有组织的设备数量
        for (let i in bfstore.state.dbOrg.datas) {
            let item = bfstore.state.dbOrg.datas[i];
            if (item.parentId.eq(org.rid)) {
                sub_org.push(item);
            }
        }

        let result = org.ownDeviceCount;
        for (let k in sub_org) {
            let orgItem = sub_org[k];
            if (orgItem.totalCount >= 0) {
                result += orgItem.totalCount;
            } else {
                // totalCount<0，则递归计算该组织的设备总数
                result += this.calcOrgHasDeviceTotalCount(orgItem);
            }

        }

        return result;
    },
    loadDeviceCount() {
        this.initOrgHasDeviceCount();
        for (let i in bfstore.state.dbDevice.datas) {
            let device = bfstore.state.dbDevice.datas[i];
            this.calcOrgHasDeviceCount(device);
        }
        for (let k in bfstore.state.dbOrg.datas) {
            let org = bfstore.state.dbOrg.datas[k];

            // 如果组织中的totalCount大于-1，则该组织已经计算过设备总数
            if (org.totalCount > -1) {
                continue;
            }
            org.totalCount = this.calcOrgHasDeviceTotalCount(org);
        }
    },
    reloadDeviceCount() {
        // 重新统计
        this.loadDeviceCount();
        // 更新组织节点
        for (let k in bfstore.state.dbOrg.datas) {
            let orgItem = bfstore.state.dbOrg.datas[k];
            this.updateTreeNodeTitle(orgItem, 1);
        }
    },
    // 自定义排序
    getRootNode() {
        return $("#orgDevTree").fancytree('getRootNode');
    },
    sortTargetChildren(target = this.getRootNode(), deep = true) {
        let sortType = false; // 设备在前组织在后或反转
        if (typeof target === 'string') {
            target = $("#orgDevTree").fancytree('getTree').getNodeByKey(target);
        }
        target.sortChildren((a, b) => {
            // 自定义 fancytree 节点排序比较方法
            // sortString 为 fancytree node 自定义属性
            let x = a.data.sortValue;
            let y = b.data.sortValue;
            // 将单位节点排在设备节点后面,sortType 为 false 则将单位和设备排序反转
            if (a.isFolder() && !b.isFolder()) {
                return sortType ? 1 : -1;
            }
            if (!a.isFolder() && b.isFolder()) {
                return sortType ? -1 : 1;
            }
            // 当排序值相等时，就以sortName定义排序顺序
            if (x === y) {
                let m = a.data.sortName;
                let n = b.data.sortName;
                return m === n ? 0 : m > n ? 1 : -1;
            }
            return x === y ? 0 : x > y ? 1 : -1;
        }, deep);
    },

    // 加载或卸载群组节点相关api
    setGroupNodeTooltip(group) {
        return group.selfId ? group.selfId + "/" + group.dmrId : group.dmrId;
    },
    setGroupNodeTitle(group, type) {
        let title = "";
        // icon
        let iconName = type === 1 ? "gw-share-group" : "gw-group";
        title += `<i class='bf-icon ${iconName}'></i>`;
        // group name
        title += `<span class="bftree_device_name">${group.name || group.dmrId}</span>`;

        return title;
    },
    setTreeGroupNode(group, type) {
        // sortValue 为节点自定义排序值，当排序值相等时使用sortName按名称排序
        // filterValue 为节点自定义过滤值

        return {
            title: this.setGroupNodeTitle(group, type),
            tooltip: this.setGroupNodeTooltip(group),
            folder: true,
            key: group.rid,
            icon: false,
            selected: false,
            sortValue: group.sortValue,
            sortName: group.name,
            filterValue: group.name
        }
    },
    addTreeGroupNode(treeId, group, type) {
        let $tree = $(treeId);
        let parentNode = $tree.fancytree("getTree").getNodeByKey("" + group.orgId);
        if (!parentNode) {
            bfconsole.error("can not found parentNode for group", group);
        }
        let child = this.setTreeGroupNode(group, type);
        return this.parentNodeAddChildren(parentNode, child);
    },
    loadGroupNodes(treeId) {
        let groups = bfstore.state.dbGroup.datas;
        let shareGroups = bfstore.state.dbShareGroup.datas;
        let loadGroup = (groupsData, type) => {
            for (let i in groupsData) {
                let data = groupsData[i];
                this.addTreeGroupNode(treeId, data, type);
            }
        };
        loadGroup(groups, 0);
        loadGroup(shareGroups, 1);
    },
    unloadGroupNodes(treeId) {
        let groups = bfstore.state.dbGroup.datas;
        let shareGroups = bfstore.state.dbShareGroup.datas;
        let loadGroup = (groupsData) => {
            for (let i in groupsData) {
                let data = groupsData[i];
                this.deleteTreeNode(data);
            }
        };
        loadGroup(groups);
        loadGroup(shareGroups);
    },
}

